package com.hdl.server;

import com.hdl.server.host.Host;
import com.hdl.server.host.HostBuilder;
import com.hdl.server.processor.RequestProcessor;
import org.dom4j.DocumentException;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * 类名 Bootstrap
 * 描述 Minicat程序启动入口类
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/5/25 16:58
 */
public class Bootstrap {
    /** 定义socket监听端口号 */
    private int port = 8080;

    private List<Host> hostList = new ArrayList<>();

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws IOException, DocumentException {
        // 加载解析相关的配置，web.xml
        loadServerConfig();

        // 定义并初始化线程池
        ThreadPoolExecutor threadPoolExecutor = initExecutor();

        // 创建Socket服务
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("========>>>Minicat start on: " +  port);
        System.out.println("=========>>>>>>使用线程池处理请求");

        // 使用线程池处理请求
        while(true) {
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, hostList);
            threadPoolExecutor.execute(requestProcessor);
        }
    }

    /**
     * 加载server.xml
     */
    private void loadServerConfig() throws IOException, DocumentException {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        List<Host> hosts = HostBuilder.builder().parseHost(inputStream);
        this.hostList = hosts;
    }


    /**
     * 初始化线程池
     */
    private ThreadPoolExecutor initExecutor(){
        // 定义一个线程池
        int corePoolSize = 10;
        int maximumPoolSize =50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue,
                threadFactory,
                handler
        );
        return threadPoolExecutor;
    }

    /**
     * Minicat程序启动入口程序
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            // 启动Minicat
            bootstrap.start();
        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }
    }
}
